<?php

class Filesystem {
	function find($strPath){
		$parts = explode("/", $strPath);

		//clear empty parts
		$size = count($parts);
		for($i = 0;  $i < $size; $i++){
			if($parts[$i] == ""){
				unset($parts[$i]);
			}
		}

		//align the indexes
		$parts = array_values($parts);

		//no path -> get root
		if(count($parts) == 0) {
			return 0;
		}

		//find the index and return it or return null on error
		return $this->find_rec($parts, 0, 0);
	}

	function find_rec($parts, $index, $parent_id) {
		global $objDatabase;

		$strSql = "SELECT * FROM `amps_fs` WHERE `parent_id` = '" . $parent_id . "' AND `name` = '" . $parts[$index] . "'";

		$cursor = $objDatabase->query($strSql);

		if($cursor !== false) {
			if($cursor->moveToFirst()) {
				if(count($parts)-1 == $index) {
					return $cursor["_id"];
				} else {
					return $this->find_rec($parts, $index+1, $cursor["_id"]);
				}
			} else {
				return -1;
			}
		} else {
			return  -1;
		}
	}

	function dirInfo($id){
		global $objDatabase;

		$strSql = "SELECT * FROM `amps_fs` WHERE `_id` = '" . $id . "'";
		$cursor = $objDatabase->query($strSql);
		if($cursor->moveToFirst()) {
			return array("_id" => $cursor["_id"], "name" => $cursor["name"]);
		} else {
			return  -1;
		}
	}

	function dirContents($id){
		global $objDatabase;

		$strSql = "SELECT * FROM `amps_fs` WHERE `parent_id` = '" . $id . "'";
		$cursor = $objDatabase->query($strSql);
		$aryContents = array();
		while($cursor->moveToNext()){
			array_push($aryContents, array("_id" => $cursor["_id"], 
										   "name" => $cursor["name"], 
										   "is_dir" => $cursor["is_dir"],
										   "mime" => $cursor["mime"],
										   "last_change" => $cursor["last_change"]));
		}

		return $aryContents;
	}
};

?>